package oyl.selenium.config.translate;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import oyl.selenium.config.AbstractDriver;
import oyl.selenium.config.translate.baidu.BaiduTranslateDemo;
import oyl.selenium.entity.Article;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Nicky.Tang on 2021/9/19 12:36 下午
 *
 * @since 02.12.10
 */
public class TranslateUtils {
    public static final String translateUrl = "https://translation.googleapis.com/language/translate/v2?key=AIzaSyBk-2bk_pUTYPZ9hnv_wsADuDTrDEbitmg";
    public static final Map<String, Map<String, String>> translateMap = new HashMap<>();
    public static final String pattern = "(?<=(src=\"|href=\")).*?(?=\")";

    public static void main(String[] args) throws Exception {
        Article article = new Article();
        article.setLanguage("ara");
        article.setTitle("CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI");
        TranslateUtils.translate(article);
    }

    public static String translateText(String text, String sourceLang, String targetLang) throws Exception {
        if (StringUtils.isEmpty(text)) {
            return text;
        }
        // 筛选出urls
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(text);
        List<String> urls = new ArrayList<>();
        while (m.find()) {
            for (int i = 0; i < m.groupCount(); i++) {
                //System.out.println(i+"Found value: " + m.group(i));
                urls.add(m.group(i));
            }
        }
        // 执行翻译
        // String res = Transan.translate(sourceLang,targetLang,text);
        // String res = DouyinTranslateDemo.translateText(sourceLang,targetLang,text);
        String res = BaiduTranslateDemo.translateText(sourceLang, targetLang, text.replaceAll(pattern, "%s"));
        // 还原urls
        res = String.format(res, urls.toArray());
        return res;
//        Map<String, String> params = new HashMap<>();

//        params.put("source", sourceLang);
//        params.put("target", targetLang);
//        params.put("q", text);
//        String responseStr = doPostRequest(translateUrl, params);
//        GoogleTranslationResponse googleTranslationResponse = JSONObject.parseObject(responseStr,GoogleTranslationResponse.class);
//        return googleTranslationResponse.getData().getTranslations().get(0).getTranslatedText();
    }

    public static void translate(List<Article> articleAll) {
        System.out.println("开始翻译。。。");
        for (Article article : articleAll) {
            translate(article);
        }
        System.out.println("结束翻译。。。\n");
    }

    public static void translate(Article article) {
        try {
            System.out.println("开始翻译: " + article.getLanguageCN());
            Map<String, String> res = new HashMap<>();
            res.put(article.getArticlebody(), BaiduTranslateDemo.translateArtice("en", article.getLanguage(), article.getArticlebody()));
            //AbstractDriver.sleepStatic(500);
            res.put(article.getTitle(), article.getTitle().substring(0, article.getTitle().indexOf(" ")+1) +
                    BaiduTranslateDemo.translateText("en", article.getLanguage(), article.getTitle().substring(article.getTitle().indexOf(" ")+1)));
           // AbstractDriver.sleepStatic(500);
            res.put(article.getFixedurl(), BaiduTranslateDemo.translateText("en", article.getLanguage(), article.getFixedurl()));
            //AbstractDriver.sleepStatic(500);
            res.put(article.getIntroduce(), BaiduTranslateDemo.translateText("en", article.getLanguage(), article.getIntroduce()));
            //AbstractDriver.sleepStatic(500);
            TranslateUtils.translateMap.put(article.getId(), res);
        } catch (Exception ex) {
            System.out.println("失败翻译: " + article.getLanguageCN());
            ex.printStackTrace();
        }
    }


    /**
     * post 请求
     *
     * @param url  请求地址
     * @param nvps 参数列表
     * @return
     */
    private static final int SOCKET_TIMEOUT_SECONDS = 60 * 1000 * 5;
    private static final int REQUEST_TIMEOUT_SECONDS = 60 * 1000 * 5;

    public static String doPostRequest(String url, Map<String, String> params) throws Exception {
//        logger.info(url);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder.build();

        HttpPost post = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(REQUEST_TIMEOUT_SECONDS)
                .setConnectTimeout(SOCKET_TIMEOUT_SECONDS)
                .setSocketTimeout(SOCKET_TIMEOUT_SECONDS)
                .build();
        post.setConfig(requestConfig);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        //		JSONArray data = new JSONArray();
        JSONObject obj = new JSONObject();
        for (String key : keySet) {
            obj.put(key, params.get(key));
            params.put(key, params.get(key));
        }
        StringEntity entity = new StringEntity(obj.toString(), HTTP.UTF_8);
        //		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
        entity.setContentType("application/json");
        post.setEntity(entity);
        final Date start = new Date();
//        logger.info("发起请求，开始时间：" + DateUtils.formatDate(start));
        CloseableHttpResponse response = httpClient.execute(post);
        final Date end = new Date();
        String resjson = EntityUtils.toString(response.getEntity());
        if (post != null) {
            post.abort();
        }
        if (httpClient != null) {
            httpClient.close();
        }
        return resjson;
    }

}
